#!/usr/bin/env python

####

# @project: UbunTube
# @version = 0.1a
# @site UbunTube http://www.ubuntube.tk
# @copyright (c) 2009 Mohamed Nashmi
# @license http://opensource.org/licenses/gpl-license.php GNU Public License

####


import sys
try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk
    import gobject
except:
    sys.exit(1)

import Debug


class Top(gobject.GObject):
    """Class representing the top toolbar in the application. Handles all the button
    callbacks for the toolbar
    """
    def __init__(self, window):
        """Creates the Top toolbar and connects all the toolbar button signals to their
        respective callbacks
        
        window = the parent Main class
        """
        self.__gobject_init__()
        
        self.wTree = window.wTree
        self.window = window
        self.topbar = self.wTree.get_widget("topbar")
        videoToolbar = self.wTree.get_widget("videotoolbar")
        videoToolbar.hide()
        #:The Remove button in toolbar. This is used to hide and show the button
        dic = { "on_toolbarAdd_clicked" : self.toolbarAdd_clicked,
                "on_toolbarSend_clicked" : self.toolbarSend_clicked,
                "on_toolbarHide_toggled" : self.toolbarHide_toggled,
                "on_toolbarFullScreen_clicked" : self.toolbarFullScreen_clicked,
                "on_meu_addVideo_activate" : self.toolbarAdd_clicked,
                "on_menu_delete_activate" : self.videotoolbarRemove_clicked,
                "on_menu_thumbnail_activate" : self.menuThumbnail_clicked,
                "on_menu_set_favorite_activate" : self.menuSetFavorite_clicked,
                "on_menu_unset_favorite_activate" : self.menuUnsetFavorite_clicked,
                "on_menu_about_activate" : self.menuAbout_clicked,
                "on_videotoolbarRemove_clicked" : self.videotoolbarRemove_clicked,
                "on_videotoolbarThumbnail_clicked" : self.menuThumbnail_clicked,
                "on_videotoolbarSetFavorite_clicked" : self.menuSetFavorite_clicked,
                "on_videotoolbarUnsetFavorite_clicked" : self.menuUnsetFavorite_clicked,}
        #:specifiys if a local video has been selected
        self.localVideoFile = None
        self.wTree.signal_autoconnect(dic)
        
    def menuSetFavorite_clicked(self, menu):
        path =  self.window.library.iconView.get_selected_items()
        try:
            path = path[0][0]
            #path -= 1
            self.window.library.setFavorite(path)
            videotoolbarSetFav = self.wTree.get_widget("videotoolbarSetFavorite")
            videotoolbarUnsetFav = self.wTree.get_widget("videotoolbarUnsetFavorite")
            videotoolbarSetFav.set_sensitive(False)
            videotoolbarUnsetFav.set_sensitive(True)
        except Exception, e:
            print e
    
    def menuUnsetFavorite_clicked(self, menu):
        path =  self.window.library.iconView.get_selected_items()
        try:
            path = path[0][0]
            #path -= 1
            self.window.library.unsetFavorite(path)
            videotoolbarSetFav = self.wTree.get_widget("videotoolbarSetFavorite")
            videotoolbarUnsetFav = self.wTree.get_widget("videotoolbarUnsetFavorite")
            videotoolbarSetFav.set_sensitive(True)
            videotoolbarUnsetFav.set_sensitive(False)
        except Exception, e:
            print e
            
    def menuThumbnail_clicked(self, menu):
        """Call back for the menu item Change thumbnail. Allows the user
        to specifiy a thumbnail for a video instead of using a randomly
        generated thumbnail."""
        thumbnail =  self.fileBrowser(menu, True)
        path = self.window.library.iconView.get_selected_items()
        try:
            path = path[0][0]
            #path -= 1
            self.window.library.changeIcon(path, thumbnail)
        except Exception, e:
            print e
        
    def menuAbout_clicked(self, menu):
        """Call back for the About menu item under Help. Shows the 
        credits and other information about the program"""
        dialog = gtk.Dialog("Add Video",
                 None,
                 gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                 (gtk.STOCK_CLOSE, gtk.RESPONSE_ACCEPT))
        container = self.window.createAboutDialog()
        dialog.set_resizable(False)
        dialog.vbox.pack_start(container, True, True, 10)
        dialog.set_size_request(350, 450)
        dialog.show_all()
        result = dialog.run()
        if result:
            dialog.destroy()

    
    
    
    def toolbarAdd_clicked(self, addButton):
        """Call back for the toolbar Add button and the Add menu Item under 
        file. Shows a dialog that prompts for a youtube link or a local
        path
        """
        dialog = gtk.Dialog("Add Video",
                 None,
                 gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                 (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                  gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        entryBox = gtk.HBox()

        container = self.createAddOptions()
        self.uTubeLink.grab_focus()
        dialog.vbox.pack_start(container)
        dialog.show_all()
        result = dialog.run()
        
        if result == gtk.RESPONSE_ACCEPT:
            #its a UTUBE LINK
            # self.localVideoFile is set only when a local file is chosen
            if not self.localVideoFile: 
                newVidURL = self.uTubeLink.get_text()
                #we want the url and not the feature related stuff
                newVidURL = newVidURL.split("&")[0]
                self.window.library.addVideo(newVidURL, False)
            else:
                newVidURL = self.localPath.get_text()
                self.window.library.addVideo(newVidURL, True)    
        
        dialog.destroy()
        
    def toolbarSend_clicked(self, sendButton):
        """Call back for the Send button in the toolbar. Still a dummy function,
        no feature implemented yet"""
        Debug.debug("SEND")
        
    def toolbarHide_toggled(self, hideButton):
        """Callback for the toolbar hide button. Shows/Hides the sidebar
        depending on its current state"""
        if hideButton.get_active():
            self.window.sideBar.hide() 
        else:
            self.window.sideBar.show()
            
    
    def toolbarFullScreen_clicked(self, fullScreenButton):
        self.window.fullScreenMode()
        
        
    def videotoolbarRemove_clicked(self, removeButton):
        """Callback for the toolbar Remove button and the Delete menu item 
        under edit. Checks that a file is selected and removes it from the 
        list and local library
        """
        warning = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, 
            "The File will be Deleted from the library, Are you sure?")
        result = warning.run()
        if result == -8 : #YES CLICKED
            path = self.window.library.iconView.get_selected_items()
            try:
                path = path[0][0]
                #path -= 1
                self.window.library.removeVideo(path)
            except Exception, e:
                print e
        
        warning.destroy()
            
    def createAddOptions(self):
        """Creates and returns a gtk.VBox() which contains the widgets for
        the add dialog"""
        container = gtk.VBox()
        uTubeRadio = gtk.RadioButton(None, "YouTube ViD")
        uTubeRadio.set_name("UT")
        uTubeRadio.set_active(True)
        uTubeRadio.connect("toggled", self.optionChanged)
        #:gtk.Entry which would hold a youtube link
        self.uTubeLink = gtk.Entry()
        
        self.localBox = gtk.HBox()
        #:gtk.Entry which would hold a local path
        self.localPath = gtk.Entry()
        localBrowse = gtk.Button("Browse")
        localBrowse.connect("clicked", self.fileBrowser)
        localRadio = gtk.RadioButton(uTubeRadio, "Local ViD")
        localRadio.set_name("LV")
        localRadio.connect("toggled", self.optionChanged)
        
        self.localBox.pack_start(self.localPath)
        self.localBox.pack_start(localBrowse)
        self.localBox.set_sensitive(False)
        
        container.pack_start(uTubeRadio, False, False)
        container.pack_start(self.uTubeLink, False, False)
        container.pack_start(localRadio, False, False)
        container.pack_start(self.localBox, False, False)
        
        return container
        
        
    def optionChanged(self, widget):
        """Call back for when the radio widget is changed. The Radio
        widget has radio buttons which specify if the file to be
        added is a Youtube link or a local file"""
        if widget.get_active():
            for radioButton in widget.get_group():
                if radioButton.get_active():
                    name = radioButton.get_name()
            if name == "LV":
                self.uTubeLink.set_sensitive(False)
                self.localBox.set_sensitive(True)
            elif name == "UT":
                self.localBox.set_sensitive(False)
                self.uTubeLink.set_sensitive(True)
                
    def fileBrowser(self, widget, thumbnail=False):
        """Creates the file browser dialog for when the Browse button is 
        clicked. Includes a gtk.FileFilter which specifies video files
        only"""
        chooser = gtk.FileChooserDialog(title="Select File",action=gtk.FILE_CHOOSER_ACTION_OPEN,
        buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
    
        filter = gtk.FileFilter()
        if thumbnail:
            filter.set_name("Image Files")
            filter.add_mime_type("image/*")
        else:
            filter.set_name("Video Files")
            filter.add_mime_type("video/*")
            
        chooser.add_filter(filter)
    
        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            if thumbnail:
                image =  chooser.get_filename()
                chooser.destroy()
                return image
            else:
                self.localVideoFile = chooser.get_filename()
                self.localPath.set_text(self.localVideoFile)

            chooser.destroy()
            
            
    def hide(self):
        self.topbar.hide()
            
            
    def show(self):
        self.topbar.show()
           
class Side(gobject.GObject):
    """Class which represents the sidebar of the application. Functionality
    is still to be implemented."""
    
    __gsignals__ = {
        "showLibrary": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
        "showFavorites" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
        }
        
        
    def __init__(self, window):
        """Creates the Sidebar object
        
        window = the parent Main class
        """
        self.__gobject_init__()
        self.wTree = window.wTree
        
        self.sideWindow = self.wTree.get_widget("sideBox")
        
        self.library = self.createButton("Library", gtk.STOCK_HOME)
        self.favorites = self.createButton("Favorites", gtk.STOCK_ABOUT)
        self.sideWindow.pack_start(self.library, False)
        self.sideWindow.pack_start(self.favorites, False)
        self.sideWindow.show_all()
        
  
    def createButton(self,label, image):
        button = gtk.Button()
        buttonImg = gtk.image_new_from_stock(image, gtk.ICON_SIZE_BUTTON)
        buttonBox = gtk.HBox(2)
        buttonLabel = gtk.Label(label)
        buttonBox.pack_start(buttonImg, False)
        buttonBox.pack_start(buttonLabel, False)
        button.add(buttonBox)
        button.set_relief(gtk.RELIEF_NONE)
        functionName = '%s_clicked' % label.lower()
        func = getattr(self,  functionName)
        button.connect("clicked", func)
        return button
        
    def library_clicked(self, button):
#        button.set_sensitive(False)
#        self.favorites.set_sensitive(True)
        self.emit("showLibrary")
    
    def favorites_clicked(self, button):
#        button.set_sensitive(False)
#        self.library.set_sensitive(True)
        self.emit("showFavorites")

    def hide(self):
        """Hides the sidebar by hiding the scroller window"""
        self.sideWindow.hide()

    def show(self):
        """Shows the sidebar by showing the scrolled window"""
        self.sideWindow.show()        
        
gobject.type_register(Side)
